/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2)
{
    if(l1 == NULL)
        return l2;
    if(l2 == NULL)
        return l1;
    struct ListNode *head;
    if(l1->val < l2->val) {
        head = l1;
        l1 = l1->next;
    } else {
        head = l2;
        l2 = l2->next;
    }
    struct ListNode *p = head;
    while(l1 && l2) {
        if(l1->val < l2->val) {
            p->next = l1;
            l1 = l1->next;
        } else {
            p->next = l2;
            l2 = l2->next;
        }
        p = p->next;
    }
    p->next = ((l1 == NULL) ? l2 : l1);
    return head;
}

struct ListNode *mergeKLists(struct ListNode **lists, int listsSize)
{
    struct ListNode *head = *lists;
    for(int i = 1; i < listsSize; ++i) {
        head = mergeTwoLists(head, *(lists + i));
    }
    return head;
}